package com.lzx.adx.report.support.strategy.v3.channel;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.lzx.adx.report.annnotions.ProductType;
import com.lzx.adx.report.constant.ProductChannelConstant;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 高途
 */
@Component
@Slf4j
@ProductType(ProductChannelConstant.GAOTU)
public class GaoTuReport extends AbstractProductReport {
    @Override
    public String execute(ReportDTO reportDTO, OcpxAccountDTO ocpxAccountDTO, ProductConfigDTO productConfigDTO) {
        //获取产品配置数据
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        if (StringUtils.isNotBlank(reportDTO.getImei()) && !StringUtils.contains(reportDTO.getImei(), "__")) {
            params.put("imei", reportDTO.getImei());
        }
        if (StringUtils.isNotBlank(reportDTO.getImeiSum()) && !StringUtils.contains(reportDTO.getImeiSum(), "__")) {
            params.put("imei", reportDTO.getImeiSum());
        }
        if (StringUtils.isNotBlank(reportDTO.getOaid()) && !StringUtils.contains(reportDTO.getOaid(), "__")) {
            params.put("oaid", reportDTO.getOaid());
        }
        if (StringUtils.isNotBlank(reportDTO.getOaidSum()) && !StringUtils.contains(reportDTO.getOaidSum(), "__")) {
            params.put("oaid", reportDTO.getOaidSum());
        }
        if (StringUtils.isNotBlank(reportDTO.getHash_android_id()) && !StringUtils.contains(reportDTO.getHash_android_id(), "__")) {
            params.put("androidId", reportDTO.getHash_android_id());
        }
        params.put("ip", reportDTO.getIp());
        params.put("ua", StringUtils.isNotBlank(reportDTO.getUser_agent()) ? reportDTO.getUser_agent() : "");
        String callbackUrl = String.format(productConfigDTO.getCallbackUrl(), reportDTO.getBizRequestId());
        params.put("callbackUrl",callbackUrl);
        String productKey = ocpxAccountDTO.getProductKey();
        String[] split = productKey.split(",");
        String identityId=split[0];
        String identityName=split[1];
        String secretkey=split[2];
        String channel=split[3];
        params.put("channel",channel);
        data.put("data",params);
        data.put("identityId",identityId);
        data.put("version","1.0");
        data.put("identityName",identityName);
        String dataJson= JSON.toJSONString(data);
        log.info("账号为{},点击上报请求高途产品端的原始参数为 {}", ocpxAccountDTO.getId(), dataJson);
        String req = encryptContent(secretkey, dataJson);
        Map<String, Object> formData = new HashMap<>();
        formData.put("bundleId", "com.gaotu100.superclass");
        formData.put("req",req);
        formData.put("identityId", identityId);
        String finalUrl = ocpxAccountDTO.getReportUrl();
        log.info("账号为{},点击上报请求高途产品端的完整地址为 {} 参数为：[{}]",
                ocpxAccountDTO.getId(), finalUrl,JSON.toJSONString(formData));
        String body = HttpUtil.post(finalUrl,formData);
        log.info("账号为{} 点击上报请求高途产品端响应的结果为{}", ocpxAccountDTO.getId(), body);
        ocpxAccountDTO.setFinalURL(finalUrl);
        return body;
    }


//    public static void main(String[] args) {
//        GaoTuReport chongYunReport = new GaoTuReport();
//        ReportDTO dto = new ReportDTO();
//        OcpxAccountDTO ocpxAccountDTO = new OcpxAccountDTO();
//        ocpxAccountDTO.setId("11111111111111");
//        ocpxAccountDTO.setReportUrl("https://xianzhi-monitor.umeng100.com/xianzhi/dolphin/open/app/behavior/business/click");
//        ocpxAccountDTO.setProductKey("191503,深圳市承宇齐光信息服务有限公司,e83564595701493ab57b9eec90d5f6c5,192944");
//        dto.setOaid("asssssssssssssss");
//        dto.setBizRequestId("9f6cb8cd3b954a28af45b872775d6650");
//        dto.setIp("127.0.0.1");
//        ProductConfigDTO productConfigDTO = new ProductConfigDTO();
//        productConfigDTO.setCallbackUrl("https://capi.qgxf.com.cn/v3/base/callback?requestId=%s&action=__ACTION__&action_time=__ACTION_TIME__");
//        String execute = chongYunReport.execute(dto, ocpxAccountDTO, productConfigDTO);
//        System.out.println(execute);
//    }


    /**
     * 根据secretKey对jsonStr进行加密
     */
    public String encryptContent(String secretKey, String jsonStr) {
        try {
            // 将 SecretKey 放到排序后的字符串头进行 md5 加密（32 位），再转成小写，即获得参数签名结果 sign 值。
            char[] tempArray = jsonStr.toCharArray();
            Arrays.sort(tempArray);
            String sortedJsonStr = new String(tempArray);
            String md5Str = DigestUtils.md5Hex(secretKey + sortedJsonStr);
            String sign =  md5Str.toLowerCase();

            // 拼成最终的请求串,并做 base64 编码，得到请求参数 req 的值。示例代码：req=base64(sign + 排序前 json 串)
            String result = Base64.getEncoder().encodeToString((sign + jsonStr).getBytes(StandardCharsets.UTF_8));
            // 进行urlEncode，避免特殊字符的影响
            return URLEncoder.encode(result, StandardCharsets.UTF_8.name());
        }catch (Exception e){
            log.info("encryptContent error, message: {}", e.getMessage());
        }
        return null;
    }


}